import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
// 由于找不到 '../../index.tsx' 模块，需确认 Answer 类型定义位置，此处假设在合适路径下创建类型文件单独定义
import type { Answer } from '../index.ts'
// 创建子模块
const questional = createSlice({
  name: 'questional',
  initialState: {
    questions: [],
    answersId: [] as number[],
    score: 0
  },
  reducers: {
    setQuestions(state, action) {
      state.questions = action.payload
    },
    setAnswersId(state, action: PayloadAction<number>) {
      state.answersId.push(action.payload)
    },
    //计算问卷成绩，首先计算出每个题目的分数，用一百分去除以题目总数得到一个题目的分数，然后通过answerId遍历对象的isRight的值是否为一，记录一的个数，最后用一的个数乘以每个题目的分数得到总分数
    calScore(state) {
      const everyScore = 100 / state.questions.length
      let scorenum = 0
      state.answersId.forEach(id => {
        //先得到当前id的对象
        const question: Answer | undefined = state.questions.flatMap(q => q.topic_answer).find(ans => ans.topic_answer_id === id)
        if (question && question.is_standard_answer === 1) {
          scorenum += everyScore
        }
      })
      state.score = scorenum
    }
  }
})

export const { setQuestions, setAnswersId, calScore } = questional.actions


export default questional.reducer